package com.tianhao.luo.helper;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch辅助类测试
 *
 * @author tianhao.luo@hand-china.com
 */
public class CountDownLatchDemo {
    //6个同学离开教室，才可以锁门

    // 这是一个错误的示范，会出现同学还没有走完，主线程就执行了班长锁门
    //public static void main(String[] args) {
    //    for (int i = 0; i < 6; i++) {
    //        new Thread(()->{
    //            System.out.println("第"+Thread.currentThread().getName()+"个同学离开了教室");
    //        },String.valueOf(i+1)).start();
    //    }
    //
    //    System.out.println("班长锁门了");
    //}

    public static void main(String[] args) {
        // 有几个同学要离开教室，就初始化传参几
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println("第"+Thread.currentThread().getName()+"个同学离开了教室");
                // 线程执行完毕，则计数器减一
                countDownLatch.countDown();
            },String.valueOf(i+1)).start();
        }

        try {
            // 主线程等待，直到countDownLatch变为0
            countDownLatch.await();
            System.out.println("班长锁门了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
